<?php
/**
 * User:chendenan
 * Created On 2022/3/17 0017 22:19
 */
namespace app\api\controller;
use app\common\business\Category as CategoryBus;
use app\common\lib\{Arr as ArrLib,Show as ShowLib};

class Category extends ApiBase{
    public function index(){
        try{
            $categorys = (new CategoryBus())->getCategorys();
        } catch (\Exception $e){
            trace($e->getMessage(),'error');
            return show("内部异常",config("status.error"));
        }
        if(!$categorys){
            return show("数据为空",config("status.error"));
        }
        $result = ArrLib::getTree($categorys);
        $result = ArrLib::sliceTreeArr($result);
        return show("ok",config("status.success"),$result);
    }

    /**
     * 搜索分类
     * /api/category/search/:id
     * @return array|\think\response\Json
     */
    public function search(){
        $id = input("param.id",0,"intval");
        if(!$id){
            return [];
        }
        $categoryBusObj = new CategoryBus();
        $result["name"] = $categoryBusObj->getById($id)['name'];
        $pid = 1;
        $list[0] = $categoryBusObj->getByPid($pid);
        $list[1] = $categoryBusObj->getByPId($list[0][0]['id']);
        $focus_ids[0] = array_search($id, array_column($list[0], 'id'))!==false ? $id : 0;
        if($searchId = array_search($id, array_column($list[1], 'id'))!==false){
            $focus_ids[0] = $list[1][$searchId]['pid'];
            $focus_ids[1] = $id;
        }else{
            $focus_ids[1] = 0;
        }
        //$focus_ids[1] = array_search($id, array_column($list[1], 'id'))!==false ? $id : 0;
        $result['list'] = $list;
        $result['focus_ids'] = implode(',',$focus_ids);
        return ShowLib::success($result);
    }

    /**
     * 返回ID的子分类
     * /api/category/sub/1
     * @return array|\think\response\Json
     */
    public function sub(){
        $id = input("param.id",0,"intval");
        if(!$id){
            return [];
        }
        $categoryBusObj = new CategoryBus();
        $result = $categoryBusObj->getByPid($id);
        return ShowLib::success($result);
    }
}